from typing import Annotated
from fastapi import APIRouter, Header, WebSocket, Query
from app.exception.cus_exception import InvalidGameException
from app.service.common_service import (
    get_game_id, get_user_id_by_token
)
from app.service.game_service import (
    get_enable_item, get_banhide_pets,
    get_game_state_unilateral, get_game_state_symmetry, get_game_pets_pick,
    exit_game
)
import traceback
from fastapi.responses import JSONResponse
from fastapi import WebSocketDisconnect
from app.handler.ws_manage import ws_manager, generate_event


game_router = APIRouter(
    prefix="/game",
    tags=["game"],
    responses={404: {"description": "Not found"}},
)

@game_router.websocket("/connection")
async def websocket_endpoint(websocket: WebSocket, token: Annotated[str | None, Query()] = None,):
    try:
        game_id = get_game_id(token)
    except InvalidGameException as e:
        return JSONResponse(status_code=400, content={'code': 100001, 'msg': e.message})
    user_id = get_user_id_by_token(token)
    await ws_manager.connect(game_id, user_id, websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await ws_manager.send_personal_message(game_id, user_id, generate_event("heartBeat", {}))
    except WebSocketDisconnect:
        ws_manager.disconnect(game_id=game_id, user_id=user_id)

"""
获取单方的房间信息
"""
@game_router.get("/getGameStateUnilateral")
async def get_state_unilateral(token: Annotated[str | None, Header()] = None):
    return get_game_state_unilateral(token)

"""
获取对称的房间信息
"""
@game_router.get("/getGameStateSymmetry")
async def get_state_symmetry(token: Annotated[str | None, Header()] = None):
    return get_game_state_symmetry(token)

"""
获取双方pick的精灵
"""
@game_router.get("/getGamePetsPick")
async def get_pets_pick(hidden_open: int = 1, token: Annotated[str | None, Header()] = None):
    return get_game_pets_pick(hidden_open, token)

"""
获取能选择的对象（根据phase里的item决定是精灵，套装还是属系）
"""
@game_router.get("/getEnableItem")
async def enable_item(page_no: int, page_size: int, token: Annotated[str | None, Header()] = None):
    return await get_enable_item(token, page_no, page_size)

"""
获取当前对局的公ban
"""
@game_router.get("/banHidePets")
async def banhide_pets(token: Annotated[str | None, Header()] = None):
    return await get_banhide_pets(token)

"""
退出房间
"""
@game_router.get("/exitGame")
async def e_game(token: Annotated[str | None, Header()] = None):
    return await exit_game(token)